package com.hfh.main.user.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hfh.main.common.annotate.JwtToken;
import com.hfh.main.common.resp.Result;
import com.hfh.main.user.entity.UserRoleEntity;
import com.hfh.main.user.mapper.UserRoleMapper;
import com.hfh.main.user.service.UserRoleService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 角色表 前端控制器
 * </p>
 */
@Tag(name="用户管理")
@RestController
@RequestMapping("/userRoleEntity")
public class UserRoleController {

    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private UserRoleService userRoleService;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @JwtToken
    @Operation(summary = "用户角色-列表-分页")
    @PostMapping("/listPageUserRole")
    public Result<?> listPageUserRole(@RequestParam Integer page, @RequestParam Integer pageSize) {
        //分页参数
        Page<UserRoleEntity> rowPage = new Page(page, pageSize);
        //queryWrapper组装查询where条件
        LambdaQueryWrapper<UserRoleEntity> queryWrapper = new LambdaQueryWrapper<>();
        rowPage = userRoleMapper.selectPage(rowPage, queryWrapper);
        return Result.success("数据请求成功", rowPage);
    }

    @JwtToken
    @Operation(summary = "用户角色-查询-编号")
    @PostMapping("/selectUserRoleByID/{param}")
    public Result<?> selectUserRoleByID(@PathVariable @Validated String param) {
        QueryWrapper<UserRoleEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("role_id"), param);
        if (userRoleService.count(wrapper) == 0) return Result.failure(200,"编号不存在", sdf.format(new Date()));
        return Result.success(userRoleService.getOne(wrapper));
    }

    @JwtToken
    @Operation(summary = "用户角色-查询-名称")
    @PostMapping("/selectUserRoleByName/{param}")
    public Result<?> selectUserRoleByName(@PathVariable @Validated String param) {
        QueryWrapper<UserRoleEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("role_name"), param);
        if (userRoleService.count(wrapper) == 0) return Result.failure(200,"名称不存在", sdf.format(new Date()));
        return Result.success("查询成功", userRoleService.getOne(wrapper));
    }

    @JwtToken
    @Operation(summary = "用户角色-保存")
    @PostMapping("/insert")
    public Result<?> insertUserRole(@RequestBody @Validated UserRoleEntity entity) {
        QueryWrapper<UserRoleEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("role_id"), entity.getId());
        if (userRoleService.count(wrapper) != 0) return Result.failure(200,"编号已存在", sdf.format(new Date()));
        if (userRoleService.save(entity)) return Result.success("保存成功", sdf.format(new Date()));
        return Result.failure(200,"保存失败", sdf.format(new Date()));
    }

    @JwtToken
    @Operation(summary = "用户角色-删除")
    @PostMapping("/delete/{param}")
    public Result<?> deleteUserRole(@PathVariable @Validated String param) {
        QueryWrapper<UserRoleEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("role_id"), param);
        if (userRoleService.count(wrapper) == 0) return Result.failure(200,"编号不存在", sdf.format(new Date()));
        if (userRoleService.remove(wrapper)) return Result.success("删除成功", sdf.format(new Date()));
        return Result.failure(200,"删除失败", sdf.format(new Date()));
    }

    @JwtToken
    @Operation(summary = "用户角色-修改")
    @PostMapping("/update")
    public Result<?> updateUserRole(@RequestBody @Validated UserRoleEntity entity) {
        QueryWrapper<UserRoleEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(("role_id"), entity.getId());
        if (userRoleService.count(wrapper) == 0) return Result.failure(200,"编号不存在", sdf.format(new Date()));
        if (userRoleService.updateById(entity)) return Result.success("修改成功", sdf.format(new Date()));
        return Result.failure(200,"修改失败", sdf.format(new Date()));
    }

    @Operation(summary = "用户角色-导出数据")
    @PostMapping("exportExcel")
    public void exportExcelUserRole(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("Excel数据表", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        List<UserRoleEntity> list = userRoleService.list();
        response.setHeader("Content-disposition", "attachment;filename*=" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), UserRoleEntity.class).sheet("Excel数据表").doWrite(list);
    }

    @Operation(summary = "用户角色-导入数据")
    @PostMapping("/importExcel")
    public Result<?> importExcelUserRole(MultipartFile file) {
        try {
            //获取文件的输入流
            InputStream inputStream = file.getInputStream();
            List<UserRoleEntity> list = EasyExcel.read(inputStream) //调用read方法
                    //注册自定义监听器，字段校验可以在监听器内实现
                    //.registerReadListener(new UserRoleListener())
                    .head(UserRoleEntity.class) //对应导入的实体类
                    .sheet(0) //导入数据的sheet页编号，0代表第一个sheet页，如果不填，则会导入所有sheet页的数据
                    .headRowNumber(1) //列表头行数，1代表列表头有1行，第二行开始为数据行
                    .doReadSync();//开始读Excel，返回一个List<T>集合，继续后续入库操作
            //模拟导入数据库操作
            for (UserRoleEntity entity : list) {
                userRoleService.saveOrUpdate(entity);
            }
            return Result.success("导入成功", sdf.format(new Date()));
        } catch (IOException exception) {
            throw new RuntimeException(exception);
        }
    }
}
